﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Cognex.VisionPro;
using Cognex.VisionPro.ToolBlock;
using System.IO;
using System.Drawing;
using Cognex.VisionPro.ImageFile;
using Cognex.VisionPro.Display;
using System.Drawing.Imaging;
using System.Windows.Shapes;

namespace YJYpublicClass
{
    public class VisionMethod
    {
        //sendx,sendy,sendr
        public double Send_X = 0.0;
        public double Send_Y = 0.0;
        public double Send_R = 0.0;
        public CogAcqFifoTool FifoAcq_tool = null;
        public CogRecordDisplay cogDisplaywindow = null;
        public bool SaveImageFlag = false;   //保存OK图片标志
        public bool InitFlag = false;
        public string intAllvpp()
        {
            try
            {
                外设._相机标定模块 = CogSerializer.LoadObjectFromFile(外设.SysPras.CalVpppath) as CogToolBlock;
            }
            catch (Exception ex)
            {
                return "标定程序加载失败" + ex.Message;
            }
            //try
            //{
            //    外设._相机应用模块 = CogSerializer.LoadObjectFromFile(外设.SysPras.VppFullpath) as CogToolBlock;
            //    FifoAcq_tool = 外设._相机应用模块.Tools["CogAcq"] as CogAcqFifoTool;

            //}
            //catch (Exception ex)
            //{
            //    return "应用程序加载失败" + ex.Message;
            //}
            InitFlag = true;
            return "";
        }
        public string SaveVPP(CogToolBlock Block, string Filename)
        {
            try
            {
                CogSerializer.SaveObjectToFile(Block, Filename);
                return "";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        public string LoadVPP(out CogToolBlock Block, string Filename)
        {
            Block = new CogToolBlock();
            try
            {
                Block = CogSerializer.LoadObjectFromFile(Filename) as CogToolBlock;
                return "";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        //public string VPP1Run()
        //{
        //    try
        //    {
        //        外设._相机应用模块.Run();
        //        cogDisplaywindow.Image = FifoAcq_tool.OutputImage;
        //        cogDisplaywindow.Record = 外设._相机应用模块.CreateLastRunRecord();
        //        cogDisplaywindow.Fit();
        //        if (外设._相机应用模块.RunStatus.Result != CogToolResultConstants.Accept)
        //        {
        //            //一定要保存，异常图片
        //            Saveimage(0, "", false, cogDisplaywindow);
        //            //保存窗口显示                             
        //            return "图像处理运行失败";

        //        }
        //        double Resultx, Resulty, Resultr;
        //        Resultx = (double)外设._相机应用模块.Outputs["X"].Value;
        //        Resulty = (double)外设._相机应用模块.Outputs["Y"].Value;
        //        Resultr = (double)外设._相机应用模块.Outputs["R"].Value;
        //        double r = Resultr * 180 / Math.PI;
        //        ColoredOutput.WriteLine(string.Format("拍照坐标：X{0}  Y{1} T{2}  ", Resultx.ToString("0.000"), Resulty.ToString("0.000"), r.ToString("0.00")));

        //        double DisAngle = Resultr - 外设.Calibdatas.BPD.GrabModelBP.r* Math.PI / 180 + 外设.Calibdatas.OFD.Offeset_R * Math.PI / 180;

        //        Send_R = DisAngle * 180 / Math.PI;
        //        //输出来的角度是否是-180到180

        //        //double Angle = 0;

        //        //double NewX = 0, NewY = 0;

        //        //if (DisAngle > 0)
        //        //{
        //        //    Angle = 2 * Math.PI - DisAngle;
        //        //}
        //        //else
        //        //{
        //        //    Angle = -DisAngle;
        //        //}
        //        //DisAngle = -DisAngle;  //调整的角度
        //        double X = 0, Y = 0;
        //        //结果X结果Y发送x，发送y，发送
        //        //先计算平移变化
        //        double piyix = Resultx - 外设.Calibdatas.BPD.GrabModelBP.x;
        //        double piyiy = Resulty- 外设.Calibdatas.BPD.GrabModelBP.y;
        //        //再计算旋转变化
        //        //先纠正旋转中心，因为做旋转中心时的基准点，与抓取时的基准点不一致，所以要纠正
        //        double newRotCenterx = 外设.Calibdatas.BPD.CircleRobotFitBP.x + (外设.Calibdatas.BPD.GrabBP.x-外设.Calibdatas.BPD.CircleRobotBP.x);
        //        double newRotCentery = 外设.Calibdatas.BPD.CircleRobotFitBP.y + (外设.Calibdatas.BPD.GrabBP.y - 外设.Calibdatas.BPD.CircleRobotBP.y);
        //        //然后计算角度变化导致得x，和y偏移
        //        double RotateOffsetx = (newRotCenterx - 外设.Calibdatas.BPD.GrabModelBP.x) * Math.Cos(DisAngle) + (newRotCentery - 外设.Calibdatas.BPD.GrabModelBP.y) * Math.Sin(DisAngle) - (newRotCenterx - 外设.Calibdatas.BPD.GrabModelBP.x);
        //        double RotateOffsety = (newRotCenterx - 外设.Calibdatas.BPD.GrabModelBP.x) * Math.Sin(DisAngle) + (newRotCentery - 外设.Calibdatas.BPD.GrabModelBP.y) * Math.Cos(DisAngle) - (newRotCentery - 外设.Calibdatas.BPD.GrabModelBP.y);
        //        //然后综合
        //        Send_X = piyix + RotateOffsetx + 外设.Calibdatas.OFD.Offeset_X;
        //        Send_Y = piyiy + RotateOffsety + 外设.Calibdatas.OFD.Offeset_Y;
        //        ColoredOutput.WriteLine(string.Format("SNQ_BRun坐标：X{0}  Y{1}  R{2}  ", Send_X.ToString("0.000"), Send_Y.ToString("0.000"), DisAngle.ToString("0.000")));
        //        if(SaveImageFlag)
        //        {
        //            Saveimage(0, "",true, cogDisplaywindow);
        //        }               
        //        return "";
        //    }
        //    catch (Exception ex)
        //    {
        //        return "VPP运行失败" + ex.Message;
        //    }

        //}

        public static string Saveimage(int type, string errstr, bool bisOK, Cognex.VisionPro.CogRecordDisplay RecorDis)
        {
            try
            {
                string imagefile = "";

                if (bisOK)
                {
                    imagefile = 外设.SysPras.SaveImagepath + "\\" + DateTime.Now.ToString("yyyyMMdd") + "\\" + "OK\\";
                }
                else
                {
                    imagefile = 外设.SysPras.SaveImagepath + "\\" + DateTime.Now.ToString("yyyyMMdd") + "\\" + "NG\\";
                }

                imagefile = imagefile + DateTime.Now.ToString("HHmmss") + "_" + errstr + ".bmp";
                if (!File.Exists(imagefile))
                {
                    XmlHelper.CreateDirectoryEx(imagefile);
                }
                Cognex.VisionPro.ImageFile.CogImageFileTool saveima = new Cognex.VisionPro.ImageFile.CogImageFileTool();
                if (RecorDis.Image != null)
                {
                    saveima.InputImage = RecorDis.Image;
                    saveima.Operator.Open(imagefile, CogImageFileModeConstants.Write);
                    saveima.Run();
                }
                else
                {
                    myLog4.Info("图片保存失败:图片为空" + type.ToString());
                }
                return "";
            }
            catch (Exception ex)
            {
               myLog4.Info( "图片保存失败:" + type.ToString() + ex.Message);
                return ex.Message;
            }
        }


        public static string SaveimageDisp(int type, string errstr, bool bisOK, Cognex.VisionPro.CogRecordDisplay RecorDis)
        {
            try
            {
                string imagefile = "";

                if (bisOK)
                {
                    imagefile = 外设.SysPras.SaveImagepath + "\\" + DateTime.Now.ToString("yyyyMMdd") + "\\" + "OK\\";
                }
                else
                {
                    imagefile = 外设.SysPras.SaveImagepath + "\\" + DateTime.Now.ToString("yyyyMMdd") + "\\" + "NG\\";
                }

                imagefile = imagefile + DateTime.Now.ToString("HHmmss") + "_" + errstr + ".jpg";
                if (!File.Exists(imagefile))
                {
                    XmlHelper.CreateDirectoryEx(imagefile);
                }
                Cognex.VisionPro.ImageFile.CogImageFileTool saveima = new Cognex.VisionPro.ImageFile.CogImageFileTool();
                if (RecorDis.Image != null)
                {
                    saveima.InputImage = RecorDis.Image;
                    saveima.Operator.Open(imagefile, CogImageFileModeConstants.Write);
                    saveima.Run();
                }
                else
                {
                    myLog4.Info("图片保存失败:图片为空" + type.ToString());
                }
                return "";
            }
            catch (Exception ex)
            {
                myLog4.Info("图片保存失败:" + type.ToString() + ex.Message);
                return ex.Message;
            }
        }

        public static string SaveimageDisp(string filebisOK, string houzui, Cognex.VisionPro.CogRecordDisplay RecorDis)
        {
            try
            {
                string imagefile = "";               
                imagefile = 外设.SysPras.SaveImagepath + "\\" + filebisOK + "\\" + DateTime.Now.ToString("yyyyMMdd") + "\\";                
                if (!File.Exists(imagefile))
                {
                    XmlHelper.CreateDirectoryEx(imagefile);
                }

                string imgName = "";
                imgName = imagefile + "\\" + DateTime.Now.ToString("HHmmssff") + ".jpg";
                Cognex.VisionPro.ImageFile.CogImageFileTool saveima = new Cognex.VisionPro.ImageFile.CogImageFileTool();
                if (RecorDis.Image != null)
                {
                    //saveima.InputImage = RecorDis.
                    saveima.InputImage = RecorDis.Image;
                    saveima.Operator.Open(imgName, CogImageFileModeConstants.Write);
                    saveima.Run();
                    //  RecorDis.cre
                }
                else
                {
                    myLog4.Info("图片保存失败:图片为空");
                }
                return "";
            }
            catch (Exception ex)
            {
                myLog4.Info("图片保存失败:"  + ex.Message);
                return ex.Message;
            }
        }

        public static string SaveimageDispjietu(string filebisOK, string houzui, Cognex.VisionPro.CogRecordDisplay RecorDis)
        {
            try
            {
                string imagefile = "";
                imagefile = 外设.SysPras.SaveImagepath + "\\" + filebisOK + "\\" + DateTime.Now.ToString("yyyyMMdd") + "\\";               
                if (!File.Exists(imagefile))
                {
                    XmlHelper.CreateDirectoryEx(imagefile);
                }

                string imgName = "";
                imgName = imagefile + "\\" + DateTime.Now.ToString("HHmmssff") + "\\" + houzui + ".jpg";
                //   Cognex.VisionPro.ImageFile.CogImageFileTool saveima = new Cognex.VisionPro.ImageFile.CogImageFileTool();
                if (RecorDis.Image != null)
                {
                    //saveima.InputImage = RecorDis.
                    Bitmap saveimagec = RecorDis.CreateContentBitmap(CogDisplayContentBitmapConstants.Image) as Bitmap;
                    saveimagec.Save(imgName, ImageFormat.Jpeg);
          
                }
                else
                {
                    myLog4.Info("图片保存失败:图片为空");
                }
                return "";
            }
            catch (Exception ex)
            {
                myLog4.Info("图片保存失败:"  + ex.Message);
                return ex.Message;
            }
        }

        /// <summary>
        /// 固定间隔删除文件
        /// </summary>
        /// <param name="FilePath"></param>
        /// <param name="Interval"></param>
        public static void DeleteFile(string FilePath, int Interval)
        {
            try
            {
                DirectoryInfo rootDirInfo = new DirectoryInfo(FilePath);
                DateTime NowTime = DateTime.Now;
                FileSystemInfo[] dirs = rootDirInfo.GetFileSystemInfos();

                foreach (var item in dirs)
                {
                    DateTime CreateFileTime = item.CreationTime;
                    TimeSpan OutTime = NowTime - CreateFileTime;
                    if (OutTime.Days > Interval)
                    {
                        FileAttributes Attr = File.GetAttributes(item.FullName);
                        if (Attr == FileAttributes.Directory) { Directory.Delete(item.FullName, true); }
                        else { item.Delete(); }
                    }
                }
            }
            catch (Exception ex)
            {
                myLog4.Info("删除文件失败" + ex.ToString());
            }
        }
        public static void drawrectangle(Cognex.VisionPro.CogRecordDisplay RecorDis, double x1, double y1, double width, double height, CogColorConstants color)
        {
            CogRectangle rect1 = new CogRectangle();
            rect1.X = x1;
            rect1.Y = y1;
            rect1.Width = width;
            rect1.Height = height;
            rect1.Color = color;
            RecorDis.StaticGraphics.Add(rect1, "a");
        }
        public static void draw_text(Cognex.VisionPro.CogRecordDisplay RecorDis, double X, double Y, double Rotation, string text, CogColorConstants color1, int size)
        {
            CogGraphicLabel str = new CogGraphicLabel();
            str.SetXYText(X, Y, text);
            str.Rotation = Rotation;
            str.Color = color1;
            str.Font = new System.Drawing.Font("宋体", size, FontStyle.Regular);
            RecorDis.StaticGraphics.Add(str, "b");
        }
        public static void draw_point(Cognex.VisionPro.CogRecordDisplay RecorDis, double X, double Y, CogColorConstants color1)
        {
            CogPointMarker point = new CogPointMarker();
            point.X = X;
            point.Y = Y;
            point.Color= color1;

            RecorDis.StaticGraphics.Add(point, "a");
        }
        public static void draw_circle(Cognex.VisionPro.CogRecordDisplay RecorDis, double X, double Y, double r, CogColorConstants color1)
        {
            try
            {
                CogCircle point = new CogCircle();
                point.CenterX = X;
                point.CenterY = Y;
                point.Color = color1;
                point.Radius = r;

                RecorDis.StaticGraphics.Add(point, "a");
            }
            catch (Exception ex)
            {

            }

        }
    }
}
